import cv2
import numpy as np
from mss import mss
import time

# 定义录制区域
monitor = {"top": 40, "left": 0, "width": 800, "height": 600}

# 创建一个VideoWriter对象
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (monitor["width"], monitor["height"]))

# 创建一个mss实例
sct = mss()

# 录制时间（秒）
record_seconds = 10

start_time = time.time()

while(int(time.time() - start_time) < record_seconds):
    # 获取屏幕截图
    img = sct.grab(monitor)

    # 将图像转换为OpenCV格式
    img_np = np.array(img)

    # 将BGR转换为RGB
    frame = cv2.cvtColor(img_np, cv2.COLOR_BGRA2BGR)

    # 写入帧
    out.write(frame)

    # 显示录制画面（可选）
    cv2.imshow('Screen Recording', frame)

    # 按'q'键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放资源
out.release()
cv2.destroyAllWindows()
